﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text;

namespace Cemit.PolyServer
{
    /// <summary>
    /// 提供使用Server对象获取控制台输入的扩展
    /// </summary>
    public static class ServerConsoleReadExtensions
    {
        public static PolyServer AddConsoleRead(this PolyServer server, out string value, Func<string, bool> condition, string hit = null, string errorHit = null)
        {
            return server.AddConsoleRead(out value, condition, s => s, hit, errorHit);
        }

        public static PolyServer AddConsoleRead<T>(this PolyServer server, out T value, Func<string, bool> condition,
            Func<string, T> converter, string hit = null, string errorHit = null)
        {
            value = Debug.Read(condition, converter, hit, errorHit);
            return server;
        }

        public static PolyServer AddIpAndPortRead(this PolyServer server, out string ip, out int port)
        {
            server.AddConsoleRead(out ip, IsIp, "IP: ", "无效的地址!")
                .AddConsoleRead(out port, IsPort, int.Parse, "Port: ", "端口范围为[1025, 65534]");

            return server;

            bool IsIp(string p)
                => IPAddress.TryParse(p, out _);

            bool IsPort(string p)
                => int.TryParse(p, out int i) && i >= 1025 && i <= 65534;
        }
    }
}
